package org.sc.learn.server.auth.security;

import org.sc.learn.server.auth.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Set;

/**
 * @author qianwx
 */
//@Service
public class DomainUserDetailService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepository.findOneByUsername(username).map(user -> {
            Set<GrantedAuthority> authorities = user.getAuthorities();
            return new User(user.getUsername(), user.getPassword(), authorities);
        }).orElseThrow(() -> new UsernameNotFoundException("user " + username + " not exists"));
    }
}
